var doSearching=false;
var doSearchingLocal = false;
var prevStr = "";
var cntQueue = 0;
var dtFirst;
var dtSecond;
var keyEventArray;
var timeHanlder;
var cntWork = 0;
var curCategory = 'Knowledge';
	
$(document).ready(function() {
	$("#queryInput").focus( );
	$("#queryInput").keyup( putQueryInput );
	
	$("#loading").ajaxStart(function(){
		   $(this).fadeIn(300);
		 });
	
	$("#loading").ajaxStop(function(){
		   $(this).fadeOut(300);
		 });
	$("#DiaryBtn").makeFloat({x:"current",y:20,speed:"fast"});
	$("#forumBtn").makeFloat({x:"current",y:120,speed:"fast"});
	
	$("#diaryWrap").makeFloat({x:10,y:80,speed:"fast"});
});


function Popup(url,target,flag) 
{
	var openObj = window.open(url,target,flag,false);
}

function doGetSuggestResult(){
	
	if($("#queryInput").val().length>0){
		getSuggestData($("#queryInput").val());
	}
}
function suggestItemClickHandler(eventObject){
	$("#queryInput").val(eventObject.currentTarget.id);
	prevStr = eventObject.currentTarget.id;
	doGetSuggestResult();
	$("#queryInput").focus();
}


function putQueryInput(event){
	
	if(event.keyCode==13){return;}
	
	if(prevStr!=$("#queryInput").val()){
		doGetSuggestResult();
	}
	
	if($("#queryInput").val().length>0)
		prevStr = $("#queryInput").val();
	else{
		emptyInput();
		prevStr = "";
	}
	
	
	return;
}


function getSuggestData(q){
	q = $.trim(q);
	//네이버 검색어 제안 ajax 호출
	var isValidReq = false;
	$.ajax({ 
	  type: "POST", 
	  url: "suggestResult.jsp", 
	  data: "q="+encodeURI($.trim($("#queryInput").val())),
	  beforeSend: function(){
	     // Handle the beforeSend event
		if($.trim($("#queryInput").val())==q)isValidReq = true;		
	   },
	  success: function(data){
		if($.trim($("#queryInput").val())==q && isValidReq){
			
	    	$("#suggestLayer").html(data);
	    	$(".suggestResultItem").click( suggestItemClickHandler );
	    	
			//네이버 바로가기 ajax호출
			$.ajax({ 
				  type: "POST", 
				  url: "shortcutResult.jsp", 
				  data: "q="+encodeURI($.trim($("#queryInput").val())),
				  success: function(data){
					if($.trim(data).length>1)
				    	$("#shortcutLayer").html($.trim(data)).show("slide", { direction: "down" }, 200);
					else
						$("#shortcutLayer").html('');
				  } 
				});
		}
	  } 
	});
}


function emptyInput(){
	$("#suggestLayer").html('');
	$("#shortcutLayer").html('');
	$("#localLayer").html('');
	$("#loadingBar").fadeOut(200);
}


var diaryLoaded = false;
var diaryVisible = false;
function loadDiaryWrapContent(){
	$("#diaryWrap").load("./lounge.jsp").css({"opacity":1,"display":"none"}).fadeIn(300);
}
function toggleDiary(){
	if(!diaryLoaded){
		$("#forumBtn").animate({
			left:$("#diaryWrap").width()-30+'px'
			},300,function(){$("#forumBtn").makeFloat({x:"current",y:120,speed:"fast"});
		});
		$("#DiaryBtn").animate({
				left:$("#diaryWrap").width()-30+'px'
			},300,
			function(){
				$("#DiaryBtn").makeFloat({x:"current",y:20,speed:"fast"});
				loadDiaryWrapContent();
				//$("#wrap").css("margin","0 0 0 250px");
				diaryLoaded = true;
				diaryVisible = true;
			});
		
	}else{
		if(diaryLoaded && diaryVisible){
			//데이터 있고 보일때
			if($("#memberSeq").val())
				tinyMCE.get('diaryContent').hide();
			$("#diaryWrap").animate({
				opacity:0
				},
				300,
				function(){
					diaryVisible = false;
					$("#diaryWrap").hide();
			});
			$("#forumBtn").animate({
				left:0
				},300,function(){$("#forumBtn").makeFloat({x:"current",y:120,speed:"fast"});
			});
			
			$("#DiaryBtn").animate({left:0},300,function(){
				$("#DiaryBtn").makeFloat({x:"current",y:20,speed:"fast"});
				//$("#wrap").css("margin","0 auto");
			});
		}else{
			//데이터는 있는데 안보일때
			if($("#memberSeq").val())
				tinyMCE.get('diaryContent').show();
			$("#forumBtn").animate({
				left:0
				},300,function(){$("#forumBtn").makeFloat({x:"current",y:120,speed:"fast"});
			});
			
			$("#forumBtn").animate({
				left:$("#diaryWrap").width()-30+'px'
				},300,function(){$("#forumBtn").makeFloat({x:"current",y:120,speed:"fast"});
			});
			
			$("#DiaryBtn").animate({
				left:$("#diaryWrap").width()-30+'px'
			},300,
			function(){
				$("#DiaryBtn").makeFloat({x:"current",y:20,speed:"fast"});
				$("#diaryWrap").css({"opacity":1,"display":"none"}).fadeIn(300);
				//$("#wrap").css("margin","0 0 0 250px");
				diaryVisible = true;
			});
		}
	}
}

function getTwitterAuthPage(){
	Popup("./toAuthPage.jsp","_blank","width=850,height=450");
}

function regSuccess(obj){
	$("#userTwitImg").attr("src",obj.MEMBER_IMG);
	$("#userTwitLink").attr("href",obj.MEMBER_URL);
	$("#userTwitName").html(obj.MEMBER_NICK);
	$("#userTwitWrap").fadeIn(300);
}


function saveDiary(){
	var checked = false;
	var shareTwit = "";
	checked = $("#shareTwitCheck").attr("checked"); 
	if(checked)shareTwit = "1";
	if($.trim($("#diaryTitle").val()).length<1){
		alert('Check your title');
		return;
	}else if($.trim(tinyMCE.get('diaryContent').getContent()).length<1){
		alert('Check your content');
		return;
	}else{
		$("#diarySaveBtn").attr("disabled","true");
		$("#diarySaveBtnBg").append(addLoadingStr).fadeIn(300);
		$.ajax({
			type:"POST",
			url:"saveDiary.jsp",
			data: "share="+shareTwit+"&title="+encodeURI($("#diaryTitle").val())+"&content="+escape(encodeURI(tinyMCE.get('diaryContent').getContent())),
			success:function(data){
				$("#addLoading").remove();
				if($.trim(data)=="success"){
					$("#diaryTitle").val('');
					tinyMCE.get('diaryContent').hide();
					$("#diaryContent").val('Make your own diary!');
					tinyMCE.get('diaryContent').show();
					getForumList();
					$("#diarySaveBtn").attr("disabled","");
				}else{
					alert('Something wrong,Try again');
					$("#diarySaveBtn").attr("disabled","");
				}
			}
		});
	}
}


function createMap(x,y){
	var mapObj = new NMap(document.getElementById('mapLayer'),300,300);
	mapObj.setCenterAndZoom(new NPoint(x,y),3);
}
function closeVideoLayer(){
	$("#videoPlayerLayer").html('');
	$("#videoPlayerTitle").html('');
	$("#videoPlayerBg").hide("slide", { direction: "up" }, 200);
}

function showVideo(obj){
	$("#videoPlayerBg").css("top",$(obj).offset().top-300);
	$("#videoPlayerTitle").html($(obj).attr('title'));
	$("#videoPlayerBg").show("slide", { direction: "up" }, 200);
	swfobject.embedSWF($(obj).attr('url'),
			"videoPlayerLayer","460","400","9.0.0",
			false,
			null,
			{wmode:"transparent",allowScriptAccess:"always"},
			{id:"videoPlayerLayer"});
}

function closeMapLayer(){
	$("#MapLayer").html('');
	$("#mapTitle").html('');
	$("#showMapBg").hide("slide", { direction: "up" }, 200);
}

function showMap(obj){
	$("#showMapBg").css("top",$(obj).offset().top-300);
	$("#mapTitle").html($(obj).attr('title'));
	$("#showMapBg").show("slide", { direction: "up" }, 200);
	
	var myLatlng = new google.maps.LatLng($(obj).attr('mapx'),$(obj).attr('mapy'));
  var myOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  
  var map = new google.maps.Map(document.getElementById("MapLayer"), myOptions);
    
  var marker = new google.maps.Marker({
      position: myLatlng, 
      map: map, 
      title: "'"+$(obj).attr('title')+"'"
  });
  
  var contentString = "<div><p style='font-size:11px;'><b>"+
  		$(obj).attr('title')
  		+"</b>  <a style='font-size:10px;' target='_blank' href='"
  		+$(obj).attr('aboutlink')+"'>"+
	  "more info"+
	  '</a><p>  <p></div>';
  
  var infowindow = new google.maps.InfoWindow({
	  content: contentString
	});
  
  
  infowindow.open(map,marker);
}

function viewMore(){
	$("#moreBtn").hide();
	$("#resultLoadingBar").fadeIn(300);
	var pre = new Number($("#curpage").val());
	$("#curpage").val(++pre);
	
	doSearchMore();
	
}

function searchResultInit(){
	$("#moreBtn").hide();
	$("#curpage").val(1);
	$("#resultLoadingBar").fadeIn(300);

	doSearch();
}

function doSearch(){
	if(!doSearching){
		doSearching = true;
		$.ajax({ 
		  type: "POST", 
		  url: "resultContent.jsp", 
		  data: "category="+$("#curCategory").val()+"&q="+encodeURI($("#queryInput").val()), 
		  success: function(data){
			$("#moreBtn").show();
			doSearching = false;
			hideLoadingBar();
		    $("#resultLayer").html(data);
		    $("#ourQueryLayer").fadeIn(300);
		  } 
		});
	}
}

function doSearchMore(){
	if(!doSearching){
		doSearching = true;
		$.ajax({ 
		  type: "POST", 
		  url: "resultContent.jsp", 
		  data: "category="+$("#curCategory").val()+"&page="+$("#curpage").val()+"&q="+encodeURI($("#queryInput").val()), 
		  success: function(data){
			
			var cur = new Number($("#curpage").val());
			
			if($("#curCategory").val()=='Image')
				$("#countOfResult").html(cur*20);
			else
				$("#countOfResult").html(cur*5);
			$("#moreBtn").show();
			doSearching = false;
			hideLoadingBar();
		    $("#resultLayer").append(data);
		  } 
		});
	}
}

function hideLoadingBar(){
	if(!doSearching && !doSearchingLocal)
		$("#resultLoadingBar").fadeOut(200);
}

function getSearchResult(){
	$.ajax({
		type:"POST",
		url:"result.jsp",
		data: "category="+curCategory+"&q="+$("#queryInput").val(),
		success:function(data){
			$("#wrap").html(data).css("opacity",0);
			$("#wrap").animate({opacity:1},200);
			searchResultInit();
		}
	});
	return false;
}

function getSearchResultQuery(query){
	$.ajax({
		type:"POST",
		url:"result.jsp",
		data: "category="+curCategory+"&q="+query,
		success:function(data){
			$("#wrap").html(data).css("opacity",0);
			$("#wrap").animate({opacity:1},200);
			searchResultInit();
		}
	});
}

function getSearchResultCategoryQuery(query,category){
	curCategory = category;
	$.ajax({
		type:"POST",
		url:"result.jsp",
		data: "category="+category+"&q="+query,
		success:function(data){
			$("#wrap").html(data).css("opacity",0);
			$("#wrap").animate({opacity:1},200);
			searchResultInit();
		}
	});
}
var forumVisible = false;
function toggleForum(){
	if(!forumVisible)
		getForumList();
	else
		hideForumList();
}

var addLoadingStr = "<span id='addLoading' style='font-style:italic;'><img  src='../images/addLoading.gif' />Processing...</span>";
function getForumList(){
	$("#forumLayer").html(addLoadingStr).fadeIn(300);
	$.ajax({
		type:"POST",
		url:"forum.jsp",
		success:function(data){
			$("#forumLayer").html(data).fadeIn(300);
			forumVisible = true;
		}
	});
}

function hideForumList(){
	$("#forumLayer").animate({opacity:0},300,function(){
		$("#forumLayer").html("").hide().css("opacity",1);
		forumVisible=false;
	});
}

function viewForumContent(forumSeq){
	var curForum = "#forumContent_"+forumSeq;
	$(curForum).fadeIn(300);
}

function closeForumContent(forumSeq){
	var curForum = "#forumContent_"+forumSeq;
	$(curForum).fadeOut(300);
}



function getShortUrl(){
	$.ajax({
		url:"http://ggl-shortener.appspot.com/?url="+ encodeURIComponent(window.location.href) + "&jsonp=googl_callback",
		success:function(data){
		alert(data);
		}
	});
	
}
